package com.example.accessingdatajpa.service.impl;

import com.example.accessingdatajpa.exception.ResourceNotFoundException;
import com.example.accessingdatajpa.picrepository.PictureRepository;
import com.example.accessingdatajpa.pojo.Picture;
import com.example.accessingdatajpa.service.IPictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Service("pictureService")
public class PictureServiceImpl implements IPictureService {
    @Autowired
    private PictureRepository pictureRepository;
    //insert a picture
    @Override
    @Transactional
    public void insertPic(Picture picture, MultipartFile file) throws IOException {
        Picture picture1 = new Picture();
        if(file==null)
        {
            picture1.setAllImg(null);
        }else {
            picture1.setAllImg(file.getBytes());
        }
        pictureRepository.save(picture1);
    }

    //find a picture by id
    @Override
    @Transactional
    public void queryPicById(Long pictureId, HttpServletResponse response) throws IOException {
        Picture picture = pictureRepository.findById(pictureId)
                .orElseThrow(() -> new ResourceNotFoundException("Picture","id",pictureId));
        byte[] data = picture.getAllImg();
        response.setContentType("image/png");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = inputStream.read(buf,0,1024))!=-1){
            outputStream.write(buf,0,len);
        }
        inputStream.close();
        outputStream.close();
    }

    //update the picture by id
    @Override
    @Transactional
    public void updatePicById(Long pictureId, MultipartFile file) throws IOException {
        Picture picture = pictureRepository.findById(pictureId)
                .orElseThrow(() -> new ResourceNotFoundException("Vegetable","id",pictureId));
        picture.setAllImg(file.getBytes());
    }
}
